package com.lagou;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;

import java.io.File;

public class SpringApplication {

    private static final String DEFAULT_PROTOCOL = "org.apache.coyote.http11.Http11NioProtocol";

    public static void run() {
        try {
            System.out.println("start tomcat9.0 begin");
            // 创建tomcat9.0实例
            Tomcat tomcat = new Tomcat();
            // 方法一:嵌入式tomcat添加Context
            Context context = tomcat.addContext("/", new File(System.getProperty("java.io.tmpdir")).getAbsolutePath());
            context.addLifecycleListener((LifecycleListener) Class.forName(tomcat.getHost().getConfigClass()).newInstance());
            // 方法二:嵌入式tomcat添加webapp
            // 需要添加tomcat-embed-jasper依赖 但不影响启动
//            tomcat.addWebapp("/", Thread.currentThread().getContextClassLoader().getResource("").getPath());
            Connector connector = new Connector(DEFAULT_PROTOCOL);
            connector.setPort(8080);
            connector.setThrowOnFailure(true);
            tomcat.getService().addConnector(connector);
            // 启动tomcat
            tomcat.start();
            System.out.println("start tomcat9.0 success");
            tomcat.getServer().await();
        } catch (Exception e) {
            System.out.println("start tomcat9.0 fail");
            e.printStackTrace();
        }
    }

}
